package com.fdq.demo.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.fdq.demo.entity.Student;
import com.fdq.demo.result.Result;
import com.fdq.demo.service.EmailService;
import com.fdq.demo.service.StudentService;
import com.fdq.demo.tool.JsonToObjectTool;
import com.fdq.demo.tool.SpiderTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: 83778
 * @date: 2023-11-14 20:53
 * @desc:
 */

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private EmailService emailService;

    @Override
    public void exportExcel(HttpServletResponse response,String token) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            List<Student> students = SpiderTool.getStudentJson(token);
//           List<Student> students = JsonToObjectTool.getStudentList("D:\\dev\\ideaProject\\fdq-dev\\src\\main\\resources\\static\\json\\1.json");

           if (students.size() > 0){

               EasyExcel.write(response.getOutputStream(), Student.class).sheet("数据字典").doWrite(students);
               //邮件提醒
               emailService.send("成功");
           }else {
               response.setContentType("application/json");
               response.setCharacterEncoding("utf-8");
               Result r = Result.ok().message("温馨提示：token超时");
               response.getWriter().write(JSON.toJSONString(r));
               emailService.send("失败");
           }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportWantExcel(HttpServletResponse response, Integer start, Integer end, String token) {

    }

    @Override
    public void exportExcelTest(String token) {
        List<Student> students = SpiderTool.getStudentJson(token);
        try {
            FileOutputStream fos = new FileOutputStream("D:\\a\\1.xlsx");
            EasyExcel.write(fos, Student.class).sheet("数据字典").doWrite(students);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    private void writeExcel(){

    }
}
